package com.mes.web.controller.biz;

import com.github.pagehelper.PageInfo;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.PurchaseProductVo;
import com.mes.biz.service.BizPayableService;
import com.mes.biz.service.BizProductService;
import com.mes.biz.service.BizPurchaseDetailService;
import com.mes.biz.service.BizPurchaseService;
import com.mes.common.annotation.Log;
import com.mes.common.core.controller.BaseController;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.domain.R;
import com.mes.common.core.page.PageDomain;
import com.mes.common.enums.BusinessType;
import com.mes.common.utils.poi.ExcelUtil;
import com.mes.framework.cache.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购单表头Controller
 * @author wy
 * @email wy
 * @date 2023-05-19
 */
@RestController
@RequestMapping("/biz/bizPurchase")
public class BizPurchaseController extends BaseController {

    @Autowired
    private BizPurchaseService bizPurchaseService;
    @Autowired
    private BizPurchaseDetailService bizPurchaseDetailService;
    @Autowired
    private BizProductService bizProductService;
    @Autowired
    private BizPayableService bizPayableService;

    /**
     * 查询采购单表头列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:list')")
    @GetMapping("/list")
    public R<PageInfo> list(BizPurchase bizPurchase, HttpServletRequest request, HttpServletResponse response) {
        bizPurchase.setPage(new PageDomain(request, response));
        PageInfo<BizPurchase> page = bizPurchaseService.findPage(bizPurchase);
        for (int i = 0; i < page.getList().size(); i++) {
            List<BizPurchaseDetail> detailList = bizPurchaseDetailService.getBizPurchaseDetailByPurchaseCode(page.getList().get(i).getPurchaseCode());
            for (int j = 0; j < detailList.size(); j++) {
                BizProduct bizProduct = bizProductService.getBizProductByProductCode(detailList.get(j).getProductCode());
//                detailList.get(j).setBrand(bizProduct.getBrand());
//                detailList.get(j).setSpec(bizProduct.getSpec());
//                detailList.get(j).setColor(bizProduct.getColor());
//                detailList.get(j).setUnit(bizProduct.getUnit());
                detailList.get(j).setBizProduct(bizProduct);
            }
            page.getList().get(i).setDetailList(detailList);
            List<BizPayable> payList = bizPayableService.getBizPayableByPurchaseCode(page.getList().get(i).getPurchaseCode());
            page.getList().get(i).setPayList(payList);
        }
        return R.data(page);
    }

    /**
     * 获取采购单表头详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:query')")
    @GetMapping(value = "/{id}")
    public R<BizPurchase> detail(@PathVariable("id") String id) {
        return R.data(bizPurchaseService.get(id));
    }

    /**
     * 新增采购单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:add')")
    @Log(title = "新增采购单", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated BizPurchase bizPurchase) {
        return R.status(bizPurchaseService.createPurchase(bizPurchase));
    }

    /**
     * 修改采购单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:edit')")
    @Log(title = "修改采购单", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated BizPurchase bizPurchase) {
        return R.status(bizPurchaseService.updatePurchase(bizPurchase));
    }

    /**
     * 删除采购单
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:remove')")
    @Log(title = "删除采购单", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/{id}")
    public R remove(@PathVariable String id) {
        BizPurchase bizPurchase = bizPurchaseService.get(id);
        String purchaseCode = bizPurchase.getPurchaseCode();
        if (bizPurchase.getStatus() != 1){
            return R.fail("待审核的订单才能删除");
        }
        boolean res = bizPurchaseService.remove(bizPurchase);
        if(res) {
            List<BizPurchaseDetail> bizPurchaseDetails = bizPurchaseDetailService.getBizPurchaseDetailByPurchaseCode(purchaseCode);
            if(bizPurchaseDetails.size() > 0) {
                List<String> idList = bizPurchaseDetails.stream().map(BizPurchaseDetail::getId).collect(Collectors.toList());
                String[] ids = idList.toArray(new String[idList.size()]);
                bizPurchaseDetailService.deleteBizPurchaseDetailByIds(ids, BaseEntity.DEL_FLAG_DELETE);
            }
        }
        return R.status(res);
    }

    /**
     * 删除采购单明细
     */
    @Log(title = "删除采购单明细", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/detail/{id}")
    public R removeDetail(@PathVariable("id") String id) {
        BizPurchaseDetail bizPurchaseDetail = bizPurchaseDetailService.get(id);
        boolean remove = bizPurchaseDetailService.remove(bizPurchaseDetail);
        return R.status(remove);
    }

    /**
     * 审核
     */
    @PreAuthorize("@ss.hasPermi('biz:bizPurchase:audit')")
    @Log(title = "审核采购单", businessType = BusinessType.DELETE)
    @GetMapping(value = "/audit/{id}")
    public R auditPurchase(@PathVariable String id) {
        return R.data(bizPurchaseService.auditPurchase(id));
    }

    /**
     * 根据字典类型查询字典数据信息等其他自定义信息
     */
    @GetMapping(value = "/getInitData/{dictTypes}")
    public R getInitData(@PathVariable String dictTypes) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.putAll(DictUtils.getMultiDictList(dictTypes));
        return R.data(dataMap);
    }

    /**
     * 查询采购单明细列表
     */
    @GetMapping("/listPurchaseStat")
    public R<PageInfo> listPurchaseStat(BizPurchase bizPurchase, HttpServletRequest request, HttpServletResponse response) {
        bizPurchase.setPage(new PageDomain(request, response));
        PageInfo<PurchaseProductVo> page = bizPurchaseService.listPurchaseStatPage(bizPurchase);
        return R.data(page);
    }

    /**
     * 打印采购单明细
     */
    @GetMapping("/printPurchaseStat")
    public void export(BizPurchase bizPurchase,HttpServletResponse response) {
        List<PurchaseProductVo> list = bizPurchaseService.listPurchaseStat(bizPurchase);
        ExcelUtil<PurchaseProductVo> util = new ExcelUtil<>(PurchaseProductVo.class);
        util.printExcel(response,list, "采购明细表");
    }
}
